package com.baofu.paycore.manager.storage.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.baofu.paycore.common.exception.ManagerErrorCode;
import com.baofu.paycore.service.facade.enums.PayCoreErrorCode;
import com.baofu.paycore.common.exception.PayCoreManagerException;
import com.baofu.paycore.dal.mapper.ClearAccountMapper;
import com.baofu.paycore.dal.model.ClearAccountDO;
import com.baofu.paycore.manager.storage.Storage;
import com.system.commons.exception.BizServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 充值/提现账户资金单存储
 *
 * User: xin deng  Date: 16/4/27 ProjectName: paycore Version: 1.0
 */
@Slf4j
@Repository
public class ClearAccountManager implements Storage<ClearAccountDO> {

    /**
     * 充值/提现账户资金单Mapper
     */
    @Autowired
    private ClearAccountMapper clearAccountMapper;

    /**
     * 新增订单
     *
     * @param clearAccountDO 订单信息
     */
    @Override
    public int addOrder(ClearAccountDO clearAccountDO) {

        return clearAccountMapper.insert(clearAccountDO);
    }

    /**
     * 更新订单
     *
     * @param clearAccountDO 订单信息
     */
    @Override
    public int modifyOrder(ClearAccountDO clearAccountDO) {

        return clearAccountMapper.update(clearAccountDO);
    }

    /**
     * 废弃订单
     *
     * @param clearAccountDO 订单信息
     */
    @Override
    public int deleteOrder(ClearAccountDO clearAccountDO) {
        return 0;
    }

    /**
     * 更新解冻状态
     *
     * @param clearAccountDO    资金单
     */
    public void updateReverseFlag(ClearAccountDO clearAccountDO){
        Integer count = clearAccountMapper.updateReverseFlag(clearAccountDO);
        if(1 != count){
            log.error("更新退款主单, error:{}", PayCoreErrorCode.UPDATE_DATA_NOT_ONE);
            throw new PayCoreManagerException(PayCoreErrorCode.UPDATE_DATA_NOT_ONE);
        }
    }

    /**
     * 依支付单号查询充值/提现账户资金单信息
     *
     * @param payNo         支付单号
     * @return              资金单
     */
    public List<ClearAccountDO> queryClearAccountByPayNo(@Param("payNo") String payNo) {

        List<ClearAccountDO> list = clearAccountMapper.queryClearAccountByPayNo(payNo);
        if (CollectionUtils.isEmpty(list)) {
            log.error("依支付单号查询充值/提现账户资金单信息为空 payNo:{}", payNo);
            throw new BizServiceException(PayCoreErrorCode.EMPTY_QUERY_RESULT);
        }
        return list;
    }
}
